package com.kaifamiao.req;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

@WebServlet( "/sign/up" )
public class SignUpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置从 请求体 中读取字符数据时使用的编码
        request.setCharacterEncoding( "UTF-8" );
        // 设置向 响应体 中输出字符数据是使用的编码
        response.setCharacterEncoding( "UTF-8" );
        // 设置 响应头 中的 content-type 字段
        response.setContentType( "text/html;charset=UTF-8" );

        PrintWriter out = response.getWriter();

        /*
        // 获得所有请求参数的名称
        Enumeration<String> paramNames = request.getParameterNames();
        Iterator<String> itor = paramNames.asIterator() ;
        while( itor.hasNext() ){
            String paramName = itor.next();
            // 根据请求参数名称获得单个参数值
            // String paramValue = request.getParameter( paramName );
            // 根据请求参数名称获得所有参数值
            String[] paramValues = request.getParameterValues( paramName );
            System.out.println( paramName + " : " + Arrays.toString( paramValues ) );
            out.println( "<div>" + paramName + " : " + Arrays.toString( paramValues ) + "</div>");
        }
        */

        // 通过 getParameter 可以获取 QueryString 、GET表单、POST表单(application/x-www-form-urlencoded) 提交的数据
        String uname = request.getParameter( "username" );
        out.println( "<div>" + uname + "</div>");
        // 不能通过 getParameter 获取 enctype 为 text/plain 或 multipart/form-data 的 POST表单中的数据
        String passwd = request.getParameter( "password" );
        out.println( "<div>" + passwd + "</div>");
        String conf = request.getParameter( "confirm" );
        out.println( "<div>" + conf + "</div>");
        String gender = request.getParameter( "gender" );
        out.println( "<div>" + gender + "</div>");
        String[] hobby = request.getParameterValues( "hobby" );
        out.println( "<div>" + Arrays.toString( hobby ) + "</div>");

    }
}
